export const longpress = {
	bind(el, binding) {
		let pressTimer = null;
		let startX, startY;
		const LONGPRESS_DISTANCE_THRESHOLD = 10; // 允许的最大移动距离（像素）

		// 开始触摸
		const start = (e) => {
			if (e.type === 'click' && e.button !== 0) return; // 只处理左键点击

			startX = e.touches ? e.touches[0].clientX : e.clientX;
			startY = e.touches ? e.touches[0].clientY : e.clientY;

			// 清除之前的定时器
			if (pressTimer !== null) clearTimeout(pressTimer);

			// 设置长按定时器（默认500ms）
			pressTimer = setTimeout(() => {
				binding.value(e); // 执行绑定的方法
			}, binding.arg || 500);
		};

		// 移动
		const move = (e) => {
			if (!e.touches) return;

			const moveX = e.touches[0].clientX - startX;
			const moveY = e.touches[0].clientY - startY;

			// 如果移动距离超过阈值，取消长按
			if (Math.abs(moveX) > LONGPRESS_DISTANCE_THRESHOLD ||
				Math.abs(moveY) > LONGPRESS_DISTANCE_THRESHOLD) {
				clearTimeout(pressTimer);
				pressTimer = null;
			}
		};

		// 结束触摸
		const end = () => {
			clearTimeout(pressTimer);
			pressTimer = null;
		};

		// 绑定事件
		el.addEventListener('mousedown', start);
		el.addEventListener('touchstart', start);
		el.addEventListener('mousemove', move);
		el.addEventListener('touchmove', move);
		el.addEventListener('mouseup', end);
		el.addEventListener('touchend', end);
		el.addEventListener('mouseleave', end);

		// 保存事件处理函数，以便后续解绑
		el._longpress = { start, move, end };
	},

	unbind(el) {
		const handlers = el._longpress;
		if (!handlers) return;

		// 移除事件监听
		el.removeEventListener('mousedown', handlers.start);
		el.removeEventListener('touchstart', handlers.start);
		el.removeEventListener('mousemove', handlers.move);
		el.removeEventListener('touchmove', handlers.move);
		el.removeEventListener('mouseup', handlers.end);
		el.removeEventListener('touchend', handlers.end);
		el.removeEventListener('mouseleave', handlers.end);

		delete el._longpress;
	}
};